package com.admin.socketmultiplayer.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.BmobUser
import cn.bmob.v3.datatype.BmobFile
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener
import cn.bmob.v3.listener.UpdateListener
import cn.bmob.v3.listener.UploadFileListener
import com.admin.socketmultiplayer.R
import com.admin.socketmultiplayer.bean.MyUser
import com.admin.socketmultiplayer.config.DataUtils
import com.admin.socketmultiplayer.config.RequestCode
import com.admin.socketmultiplayer.dialog.UserInfoChangeDialog
import com.socks.library.KLog
import kotlinx.android.synthetic.main.activity_user_info.*
import me.nereo.multi_image_selector.MultiImageSelectorActivity
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.io.File
import java.io.ByteArrayOutputStream
import java.io.FileOutputStream


/**
 * Created by 吴昶 on 2018/5/9.
 */
class UserInfoActivity:BaseActivity(){

    var path=""
    var savePath=Environment.getExternalStorageDirectory().path+"/cut.png"
    var user:MyUser?=null
    var dialog:UserInfoChangeDialog?=null

    override fun bindLayout(): Int {
        return R.layout.activity_user_info
    }

    override fun initData(){
        initUserInfo()
        DataUtils.showUserImage(this,user!!.objectId,iv_user_header)
    }

    fun initUserInfo(){
        user= BmobUser.getCurrentUser(MyUser::class.java)
        tv_user_name.text=user!!.username
        tv_user_email.text=user!!.email
        tv_user_phone.text=user!!.mobilePhoneNumber
        tv_user_qq.text=user!!.QQ
        tv_user_weichat.text=user!!.weChat
    }

    override fun initEvent() {
        linear_back.setOnClickListener { finish() }
        iv_user_header.setOnClickListener {
            startActivityForResult<MultiImageSelectorActivity>(RequestCode.GET_IMAGE,MultiImageSelectorActivity.EXTRA_SELECT_COUNT to 1)
        }

        relate_change_info.setOnClickListener {
            if(dialog==null){
                dialog= UserInfoChangeDialog(this,R.layout.dialog_user_info,R.style.cusdialog,listener)
            }
            dialog!!.show()
        }

        relate_change_password.setOnClickListener {
            if(user!!.email==null||user!!.email==""){
                toast("未设置邮箱无法修改密码，请先设置邮箱")
            }else {
                startActivity<ChangePasswordActivity>()
            }
        }

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode== Activity.RESULT_OK) when(requestCode){
            RequestCode.GET_IMAGE->{
                var images=data!!.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT)
                path=images[0]
                iv_user_header.setImageURI(DataUtils.getUriFormFile(this,images[0]))
                imageCut(images[0])
            }
            RequestCode.INT_IMAGE_CUT->{
                val bundle = data!!.extras
                var bitmapCut = bundle.getParcelable<Bitmap>("data")
                val baos = ByteArrayOutputStream()
                //compress方法是把一个位图写到一个OutputStream中,参数一是位图对象，二是格式,三是压缩的质量，四是输出流
                bitmapCut.compress(Bitmap.CompressFormat.JPEG, 100, baos)
                //保存到本地
                var save=File(savePath)
                if(!save.exists()){
                    save.createNewFile()
                }
                var out=FileOutputStream(save)
                out.write(baos.toByteArray())
                out.flush()
                out.close()
                iv_user_header.setImageBitmap(BitmapFactory.decodeFile(savePath))

                var bf=BmobFile(save)
                bf.uploadblock(object :UploadFileListener(){
                    override fun done(p0: BmobException?) {
                        p0?:let {
                            saveHeader(bf)
                        }
                        p0?.let {
                            toast("上传头像失败")
                            KLog.e(p0.message.toString())
                        }
                    }
                })


            }
        }

    }

    fun saveHeader(file:BmobFile){
        var my=MyUser()
        my.header= file
        my.update(user!!.objectId,object: UpdateListener(){
            override fun done(p0: BmobException?) {
                p0?:let { toast("更新成功") }
                p0?.let { toast("更新失败")
                    KLog.e(p0.message.toString())
                }
            }
        })
    }


    private fun imageCut(uri: String) {
        try{
            val intent = Intent("com.android.camera.action.CROP")
            intent.setDataAndType(DataUtils.getUriFormFile(this,uri), "image/*")
            // crop为true是设置在开启的intent中设置显示的view可以剪裁
            intent.putExtra("crop", "true")
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1)
            intent.putExtra("aspectY", 1)
            intent.putExtra("outputX", 320)// 输出图片大小
            intent.putExtra("outputY", 320)
            intent.putExtra("return-data", true)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)//添加这一句表示对目标应用临时授权该Uri所代表的文件
            }

            startActivityForResult(intent, RequestCode.INT_IMAGE_CUT)
        }catch (e:Exception){
            KLog.d(e.message.toString())
        }

    }

    override fun onPause() {
        super.onPause()
        if(dialog!=null && dialog!!.isShowing){
            dialog!!.cancel()
        }
    }

    var listener=object :UserInfoChangeDialog.OnCancelListener{
        override fun onCancelListener(msg: String) {
            if(msg=="r"){
                initUserInfo()
            }
        }
    }

}